import 'dart:io';
import 'dart:math';

import 'package:crypto/crypto.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:share_fit/app/controllers/home/home_const.dart';
import 'package:share_fit/app/controllers/space/person/person_const.dart';
import 'package:share_fit/app/helper/db/ute_db_helper.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/helper/storage_helper.dart';
import 'package:share_fit/generated/locales.g.dart';

import 'app_const.dart';

class AppUtil {

  static void showTips(title, message) {
    if (Get.isSnackbarOpen) {
      Get.closeCurrentSnackbar();
    }
    Get.snackbar(title, message,
        duration: const Duration(seconds: 2), animationDuration: const Duration(milliseconds: 300));
  }

  static void showDeviceDisconnectTips() {
    showTips(LocaleKeys.info.ts, LocaleKeys.device_not_connected.ts);
  }

  static int getVersionIntValue(String version) {
    List versionArr = version.split('.');
    versionArr = versionArr.map((i) => int.parse(i)).toList().reversed.toList();
    int versionCode = 0;
    for (int i = 0; i < versionArr.length;i++) {
      int value = versionArr[i]* pow(10, i);
      versionCode += value;
    }
    return versionCode;
  }

  static bool compareVersion(String newVersion, String oldVersion) {
    return getVersionCode(newVersion) > getVersionCode(oldVersion);
  }
  
  static String getVersionName(String version) {
    return version.replaceAll("V", "").replaceAll("v", "");
  }

  static int getVersionCode(String version) {
    int code = 0;
    var numbers = RegExp(r'\d+');
    var matches = numbers.allMatches(version);
    if (matches.isNotEmpty) {
      code = int.parse(matches.first.group(0).toString());
    }

    return code;
  }

  static Future<String> getFileMd5(String filePath) async {
    File file = File(filePath);
    if(!file.existsSync()) {
      return '';
    }
    List<int> bytes = await file.readAsBytes();
    Digest md5Digest = md5.convert(bytes);
    return md5Digest.toString();
  }

  static Future<String> getFilesha256(String filePath) async {
    File file = File(filePath);
    if(!file.existsSync()) {
      return '';
    }
    List<int> bytes = await file.readAsBytes();
    Digest sha256Digest = sha256.convert(bytes);
    return sha256Digest.toString();
  }

  static bool isValidMacAddress(String macAddress) {
    final pattern = RegExp(r'^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$');
    return pattern.hasMatch(macAddress);
  }

  static void clearLoginInfo() {
    StorageHelper.save('space_person_name', '');
    StorageHelper.save('user_token', '');
    StorageHelper.save('expire_time_sec', '');
    StorageHelper.save('login_state', false);
    StorageHelper.save('login_id', '');
    StorageHelper.save('space_avatar_path', '');
    StorageHelper.save('space_person_gender', -1);
    StorageHelper.save(PersonConst.spacePersonAge, -1);
    StorageHelper.save(PersonConst.spacePersonHeight, -1);
    StorageHelper.save(PersonConst.spacePersonWeight, -1);
    StorageHelper.save('sport_target_step', 0);
    StorageHelper.save('space_person_gender_text', '');
    StorageHelper.save('register_info_date', '');
  }


  static Future<void> requestPermissions() async {

    var prominentAccept = StorageHelper.read(AppConst.prominentAccept, defaultValue: false);
    var granted = await Permission.location.isGranted;
    if (!granted) {
      if (Platform.isAndroid) {
        if (prominentAccept) {
          await Permission.location.request();
        }
      }
      else {
        await Permission.location.request();
      }
    }

    if (Platform.isAndroid) {
      granted = await Permission.contacts.isGranted;
      if (!granted) {
        await Permission.contacts.request();
      }

      granted = await Permission.phone.isGranted;
      if (!granted) {
        await Permission.phone.request();
      }

      granted = await Permission.sms.isGranted;
      if (!granted) {
        await Permission.sms.request();
      }

    }
  }

  static Future<void> deleteAccountInfo({String? address}) async {
    clearLoginInfo();
    // 清除首页以及各个小组件详情页的配置项
    clearHomePageSettingsInfo();
    clearDbData(address: address);
  }

  static clearHomePageSettingsInfo() {
    StorageHelper.save(HomeConst.cycleCalendarSettingStartTime, null);
  }

  static clearDbData({String? address}) {
    UteDbHelper.cleanAllData(address: address);
  }
}